import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * hset hget
 * hexists
 * hdel
 * hkeys hvals
 * hmget hmset
 */

public class RedisHash {
    public static void main(String[] args) {
        JedisPool jedisPool = new JedisPool("tcp://127.0.0.1:8888");

        try (Jedis jedis = jedisPool.getResource()) {
//            test1(jedis);

//            test2(jedis);

//            test3(jedis);

            test4(jedis);

        }
    }

    /**
     * hmget
     * @param jedis
     */
    public static void test4(Jedis jedis) {
        jedis.flushAll();

        Map<String, String> map = new HashMap<>();
        map.put("f1", "111");
        map.put("f2", "222");
        map.put("f3", "333");
        map.put("f4", "444");
        map.put("f5", "555");

        jedis.hset("key1", map);

        List<String> values = jedis.hmget("key1", "f1", "f2", "f3");
        System.out.println(values);
    }

    /**
     * hkeys
     * hvals
     * @param jedis
     */
    public static void test3(Jedis jedis) {
        jedis.flushAll();

        Map<String, String> map = new HashMap<>();
        map.put("f1", "111");
        map.put("f2", "222");
        map.put("f3", "333");
        map.put("f4", "444");
        map.put("f5", "555");

        jedis.hset("key1", map);

        Set<String> fields = jedis.hkeys("key1"); //拿到所有 fields
        System.out.println(fields);

        List<String> values = jedis.hvals("key1"); //拿到所有 values
        System.out.println(values);
    }

    /**
     * hexists
     * hdel
     * @param jedis
     */
    public static void test2(Jedis jedis) {
        jedis.flushAll();

        Map<String, String> map = new HashMap<>();
        map.put("f1", "111");
        map.put("f2", "222");
        map.put("f3", "333");
        map.put("f4", "444");
        map.put("f5", "555");

        jedis.hset("key1", map);
        System.out.println(jedis.hexists("key1", "f3"));
        System.out.println(jedis.hexists("key1", "f6"));
        System.out.println(jedis.hexists("key2", "f6"));

        long hdel = jedis.hdel("key1", "f1", "f2", "f3", "f4", "f5");
        System.out.println(hdel);
    }

    /**
     * hset hget
     * @param jedis
     */
    public static void test1(Jedis jedis) {
        jedis.flushAll();

        Map<String, String> map = new HashMap<>();
        map.put("f1", "111");
        map.put("f2", "222");
        map.put("f3", "333");
        map.put("f4", "444");
        map.put("f5", "555");

        jedis.hset("key1", map);
        String value = jedis.hget("key1", "f3");
        System.out.println(value);

        System.out.println(jedis.hget("key2", "f1")); // key 不存在，返回 null
        System.out.println(jedis.hget("key1", "f6")); //field 不存在，返回 null
    }
}
